package com.jinchengll.xigua.network;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit客户端（单例模式）
 *
 * @author jinchengll
 * @since 2021/10/3
 */
public class RetrofitClient implements INetworkClient {

    private final static String BaseURL = "http://101.34.50.113:10520";

    private final Retrofit retrofit;
    private final Map<Class<?>, Object> serviceCache;

    private RetrofitClient() {
        retrofit = buildRetrofit();
        serviceCache = new HashMap<>();
    }

    public static RetrofitClient getInstance() {
        return RetrofitClientHolder.client;
    }

    @Override
    public <T> T getService(Class<T> clazz) {
        if (serviceCache.containsKey(clazz)) return (T) serviceCache.get(clazz);
        T service = this.retrofit.create(clazz);
        serviceCache.put(clazz, service);
        return service;
    }

    private static class RetrofitClientHolder {
        private static final RetrofitClient client = new RetrofitClient();
    }

    private Retrofit buildRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(BaseURL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    //    private final static OkHttpClient client = new OkHttpClient().newBuilder()
//            .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
//            .connectTimeout(10, TimeUnit.SECONDS)//设置请求超时时间
//            .writeTimeout(10, TimeUnit.SECONDS)//设置写入超时时间
//            .addInterceptor(new LogInterceptor())//添加打印拦截器
//            .retryOnConnectionFailure(true)//设置出现错误进行重新连接。
//            .build();
}
